local routes = {} -- a table of all possible trucking routes (markers?)
local routeNames = {} -- a table of the routes' names
local routeBlips = {} -- a table of all of the trucking routes' radar blips
local routeBaseRewards = {} -- a table of trucking routes' base rewards
local cargoTypes = {} -- a table of possible cargo types
local currentRoute -- the current trucking route
local routeTrailers = {}

local trucking = false -- is the player on a trucking route?

table.insert(routes, createMarker(30,30,30,'checkpoint'))
table.insert(routeBlips, createBlip(30,30,30,51))
table.insert(routeNames, "San Fiero Pay N' Spray")
table.insert(routeBaseRewards, 3000)
table.insert(routeTrailers, 450)

table.insert(routes, createMarker(300,300,300,'checkpoint'))
table.insert(routeBlips, createBlip(300,300,300,51))
table.insert(routeNames, "Los Angeles' Shitholes")
table.insert(routeBaseRewards, 8000)
table.insert(routeTrailers, 450)


table.insert(cargoTypes, "Components")
table.insert(cargoTypes, "Fuel")
table.insert(cargoTypes, "Packaging")
table.insert(cargoTypes, "Automobiles")

function CalculateReward(route, basereward--[[illegal]])
	local playerx, playery, playerz = getElementPosition(localPlayer)
	local stopx, stopy, stopz = getElementPosition(route)
	
	--local demand = (100 - route.currentsupplies / 100) + 0.5
	local demand = 0.6 -- FIX THIS
	local reward = (basereward + (getDistanceBetweenPoints2D(playerx, playery, stopx, stopy) / 3)) * demand
	--[[if illegal == true then
		reward = reward * 1.5
	end]]
	math.floor(reward)
	return reward
end

function TruckingSetRoute()

end

function TruckingEnterVehicle()
	if getPlayerTeam(localPlayer) == "Trucker" then
		if getPedOccupiedVehicle(localPlayer) ~= nil then
			outputChatBox(getPedOccupiedVehicle(localPlayer))
			 -- populate their radar with blips to the trucking routes
		end		
	end
end

function TruckingExitVehicle()
	if trucking == true then
		outputChatBox("Going on a cigar break eh? Well don't go too far!")
		addEventHandler("onClientRender", getRootElement(), TruckingCigarBreak)
	end
end

function TruckingCigarBreak() -- i could make this into a generic function like checkvehicledistance and add maxDistance, vehicle and mission type args
	vehiclex, vehicley, vehiclez = getElementPosition(vehicle)
	playerx, playery, playerz = getElementPosition(localPlayer)
	
	if getDistanceBetweenPoints2D (vehiclex, vehicley, playerx, playery) >= 15 then
		outputChatBox("Trucking mission failed")
		trucking = false	
		removeEventHandler("onClientRender",getRootElement(), TruckingCigarBreak)
		removeEventHandler("onClientRender",getRootElement(), TruckingCheckVehicle) -- reallocate the cycles and memory to something more useful
		removeEventHandler("onClientVehicleExit", getRootElement(), TruckingExitVehicle)
	end
end


function handleDoubleClick()
	if guiGridListGetSelectedItem(GUIEditor_Grid[1]) ~= false then
		truckingGUIChoice = guiGridListGetSelectedItem(GUIEditor_Grid[1]) -- bug: switching ordering makes this flip shit and output 13 for the first one and so on
		outputChatBox(truckingGUIChoice)
		showCursor(false)
		guiSetInputEnabled(false)
		guiSetVisible(GUIEditor_Window[1], false)
		removeEventHandler("onClientRender", getRootElement(), UpdateTable)
		
		if guiGridListGetSelectedItem(GUIEditor_Grid[1]) ~= -1 then
			trucking = true
			-- serverside: create a trailer directly behind the player's tanker with the same rotation values
		end
	end
end

function createTruckingWindow()

	GUIEditor_Window = {}
	GUIEditor_Label = {}
	GUIEditor_Edit = {}
	GUIEditor_Grid = {}
	GUIEditor_Scrollbar = {}
	guiSetInputEnabled(true)

	GUIEditor_Window[1] = guiCreateWindow(0.2359,0.2226,0.5914,0.6471,"Trucking",true)
	guiSetAlpha(GUIEditor_Window[1],1)
	guiWindowSetSizable(GUIEditor_Window[1],false)
	GUIEditor_Scrollbar[1] = guiCreateScrollBar(0.9696,0.1026,0.0185,0.7123,false,true,GUIEditor_Window[1])
	GUIEditor_Grid[1] = guiCreateGridList(0.0132,0.1026,0.9498,0.7123,true,GUIEditor_Window[1])
	
	guiGridListSetSelectionMode(GUIEditor_Grid[1],0)
	addEventHandler("onClientGUIDoubleClick", GUIEditor_Grid[1], handleDoubleClick)

	
	guiGridListAddColumn(GUIEditor_Grid[1],"Cargo Type",0.17)

	guiGridListAddColumn(GUIEditor_Grid[1],"Destination",0.20)

	guiGridListAddColumn(GUIEditor_Grid[1],"Distance",0.14)

	guiGridListAddColumn(GUIEditor_Grid[1],"Demand",0.14)

	guiGridListAddColumn(GUIEditor_Grid[1],"Reward",0.18)

	guiGridListAddColumn(GUIEditor_Grid[1],"Illegal?",0.1)

	GUIEditor_Edit[1] = guiCreateEdit(0.1638,0.8833,0.0608,0.0423,"3000",true,GUIEditor_Window[1])
	GUIEditor_Edit[2] = guiCreateEdit(0.1638,0.9316,0.0608,0.0423,"100",true,GUIEditor_Window[1]) -- TODO: update when the edit text is changed
	
	for i=1, 30 do -- magic number, it's the amount of routes and I don't know how to get rid of it
		guiGridListAddRow(GUIEditor_Grid[1])
	end
	
	local userpreference1 = tonumber(guiGetText(GUIEditor_Edit[1]))
	local userpreference2 = tonumber(guiGetText(GUIEditor_Edit[2]))
	local tableupdatecount = 0

	function UpdateTable()
		local playerx, playery, playerz = getElementPosition(localPlayer)
		local updatetable = false
						
		if guiGetText(GUIEditor_Edit[1]) == nil or false or userpreference1 < 1 then
			userpreference1 = 3000
			olduserpreference1 = 3000
		end
		
		if guiGetText(GUIEditor_Edit[2]) == nil or false or userpreference2 < 1 then -- error catching
			userpreference2 = 100
			olduserpreference2 = 100
		end
		
		local olduserpreference1 = userpreference1
		local olduserpreference2 = userpreference2
								
		if guiGetText(GUIEditor_Edit[1]) ~= nil and guiGetText(GUIEditor_Edit[2]) ~= false and tonumber(guiGetText(GUIEditor_Edit[2])) > 0 then
			userpreference1 = tonumber(guiGetText(GUIEditor_Edit[1]))
		end
	 
		if guiGetText(GUIEditor_Edit[2]) ~= nil and guiGetText(GUIEditor_Edit[2]) ~= false and tonumber(guiGetText(GUIEditor_Edit[2])) > 0 then
			userpreference2 = tonumber(guiGetText(GUIEditor_Edit[2]))
		end
		-- this buggy shit is pissing me off
		if userpreference1 ~= olduserpreference1 or userpreference2 ~= olduserpreference2 then -- unholy mother of fuck, IT CAN'T EQUAL NIL
			updatetable = true
		end
		

		
		if updatetable == true or tableupdatecount < 1 then
			for i=1, guiGridListGetRowCount(GUIEditor_Grid[1]) do
				guiGridListRemoveRow(GUIEditor_Grid[1], i)
			end
				
			for i=1, tableLength(routes) do
				local routex, routey, routez = getElementPosition(routes[i])
				local distance = getDistanceBetweenPoints2D(playerx, playery, routex, routey)
				local distance = math.floor(distance)
				if distance <= userpreference1 and CalculateReward(routes[i],routeBaseRewards[i]) >= userpreference2 and distance > 200 then -- fix the last bit
					guiGridListSetItemText(GUIEditor_Grid[1],i,1,"Components", false, false) -- TODO: figure out cargo types
					guiGridListSetItemText(GUIEditor_Grid[1],i,2,routeNames[i], false, false)
					guiGridListSetItemText(GUIEditor_Grid[1],i,3,distance, false, true)
					guiGridListSetItemText(GUIEditor_Grid[1],i,4,"0.6", false, true)  -- finish me
					guiGridListSetItemText(GUIEditor_Grid[1],i,5,math.floor(CalculateReward(routes[i],routeBaseRewards[i])), false, true)
					guiGridListSetItemText(GUIEditor_Grid[1],i,6,"No", false, false)
				end
			end	
			updatetable = false
			tableupdatecount = 1
		end
	end
	
	UpdateTable()
	
	addEventHandler("onClientRender", getRootElement(), UpdateTable)
	
	GUIEditor_Label[1] = guiCreateLabel(0.0185,0.0543,0.5667,0.0362,"Please choose a route:",true,GUIEditor_Window[1])
	GUIEditor_Label[2] = guiCreateLabel(0.4333,0.829,0.0674,0.0402,"Settings:",true,GUIEditor_Window[1])
	guiSetFont(GUIEditor_Label[2],"default-bold-small")
	GUIEditor_Label[3] = guiCreateLabel(0.0238,0.8893,0.14,0.0382,"Maximum distance:",true,GUIEditor_Window[1])
	GUIEditor_Label[4] = guiCreateLabel(0.0845,0.1992,0.0066,0.0101,"",true,GUIEditor_Window[1])
	GUIEditor_Label[5] = guiCreateLabel(0.0238,0.9396,0.1374,0.0342,"Minimum reward:",true,GUIEditor_Window[1])
	GUIEditor_Label[6] = guiCreateLabel(0.0132,0.8431,0.9868,0.0463,"______________________________________________________________________________________________________________",true,GUIEditor_Window[1])
	GUIEditor_Label[7] = guiCreateLabel(0.2325,0.8692,0.0159,0.1147,"|\n|\n|\n|",true,GUIEditor_Window[1])
	GUIEditor_Label[8] = guiCreateLabel(0.753,0.8692,0.0159,0.1147,"|\n|\n|\n|",true,GUIEditor_Window[1])
	GUIEditor_Label[9] = guiCreateLabel(0.7028,0.0543,0.2668,0.0362,"Press F1 for help regarding features",true,GUIEditor_Window[1])
	showCursor(true)
end

function TruckingCheckVehicle()
	--if getPedOccupiedVehicle(localPlayer) == "Tanker" then --fucking broken shit?
		if getVehicleTowedByVehicle(getPedOccupiedVehicle(localPlayer)) == routeTrailers[currentroute] then
			if currentroute ~= nil then
				TruckingFinishRoute(currentroute, trailer)
			end
		elseif getVehicleTowedByVehicle(getPedOccupiedVehicle(localPlayer)) == false then
			if currentroute == nil then
				TruckingStartRoute() -- hurf finish me
			end
		end
	--end
end

function TruckingStartRoute()
	createTruckingWindow() -- hurf finish me
end

function TruckingFinishRoute(currentroute, trailer) -- TODO: check if the player has a trailer and if so increase the supplies
	local reward = CalculateReward(currentroute, routesBaseRewards[currentroute])
	local passengers = getVehicleOccupants(getPedOccupiedVehicle(localPlayer))
	
	fadeCamera(false)
	for i=0, tableLength(passengers) do
		--fadeCamera(passengers[i], false) -- does this even work? move this serverside
		--setTimer(fadeCamera, 2800, 1, passengers[i], true)
		triggerServerEvent("serverGiveMoney", getRootElement(), passengers[i], reward / tableLength(passengers))
	end
	setTimer(fadeCamera, 2800, 1, true)
	detachTrailerFromVehicle(getPedOccupiedVehicle(localPlayer))
	destroyElement(trailer)
end

function tableLength(T) -- messy, make this a global function
	local count = 0
	for _ in pairs(T) do count = count + 1 end
	return count
end

for i=1, tableLength(routes) do
	addEventHandler("onClientMarkerHit", routes[i], TruckingCheckVehicle)
end
addEventHandler("onClientVehicleEnter",getRootElement(),TruckingEnterVehicle)